package com.neusoft.elmboot.controller;


import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/UserController")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @PostMapping("/getUserByIdByPass")
    public Map<String, Object> getUserByIdByPass(@RequestParam String userId, @RequestParam String password) {
        // 创建一个 User 对象封装请求参数
        User user = new User();
        user.setUserId(userId);
        user.setPassword(password);

        // 调用 service 层验证用户身份
        User loggedInUser = userService.getUserByIdByPass(user);

        if (loggedInUser != null) {
            // 生成 JWT Token
            String token = JwtUtil.generateToken(loggedInUser.getUserId());

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("token", token); // 返回 Token
            response.put("user", loggedInUser); // 返回用户信息

            return response; // 返回结果
        } else {
            throw new RuntimeException("用户名或密码错误");
        }
    }


    @GetMapping("/getUserById")
    public int getUserById(User user) throws Exception{
        return userService.getUserById(user.getUserId());
    }

    @PostMapping("/saveUser")
    public int saveUser(User user) throws Exception{
        return userService.saveUser(user);
    }


}